package com.jyu.work.controller;


import com.alibaba.druid.sql.PagerUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyu.common.context.BaseContext;
import com.jyu.common.result.PageResult;
import com.jyu.pojo.VO.OrderDetailVO;
import com.jyu.pojo.entity.Order;
import com.jyu.pojo.entity.OrderDetail;
import com.jyu.pojo.entity.Product;
import com.jyu.work.service.IOrderDetailService;
import com.jyu.work.service.IOrderService;
import com.jyu.work.service.IProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author guancheng
 * @since 2023-11-30
 */
@RestController
@RequestMapping("/orderDetail")
@CrossOrigin(origins = "http://127.0.0.1:5173")

public class OrderDetailController {

    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IProductService productService;

    @GetMapping("/page")
    public PageResult page(int page, int pageSize) {
        Page pageInfo = new Page(page, pageSize);

        Long currUserId = BaseContext.getCurrentId();

        List<Order> orderList = orderService.list(new LambdaQueryWrapper<Order>().eq(Order::getUserId, currUserId));

        List<OrderDetailVO> volist = new ArrayList<>();

        for (int i = 0; i < orderList.size(); i++) {
            Order order = orderList.get(i);

            List<OrderDetail> orderDetailList = orderDetailService.list(
                    new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, order.getId()));

            for (int j = 0; j < orderDetailList.size(); j++) {

                OrderDetail orderDetail = orderDetailList.get(j);
                OrderDetailVO orderDetailVO = new OrderDetailVO();

                BeanUtils.copyProperties(order, orderDetailVO);
                BeanUtils.copyProperties(orderDetail, orderDetailVO);
                // 设置好product
                orderDetailVO.setProduct(productService.getById(orderDetailVO.getProductId()));

                volist.add(orderDetailVO);
            }
        }

        int total = volist.size();

        if(total == 0){
            return new PageResult();
        }
        
        
        

        return new PageResult(total, volist.subList( (page-1)* pageSize, page*pageSize-1));

    }
}

